package com.sosee.cgfw.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sosee.cgfw.R;
import com.sosee.cgfw.entity.Data;
import com.sosee.cgfw.entity.PiaoJia;
import com.sosee.cgfw.entity.PiaoJiaData;
import com.sosee.cgfw.entity.PiaoJiaJson;
import com.sosee.cgfw.entity.ad.DataJson;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.sosee.cgfw.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Thinkpad on 2016/2/22.
 * 我的票夹界面  时间定为功能待优化
 */
public class MyTicketActivity extends Activity implements View.OnClickListener {
    private RelativeLayout rl;
    List<Integer> plist=new ArrayList<Integer>();
    private int margin;
    private int total=5;
    private int size=4;
    private int height;
    private Map<Integer,View> map=new HashMap<Integer, View>();
    private List<Integer> posList=new ArrayList<Integer>();//用于记录view 的初始位置  方便计算 偏移量
    private boolean isZhankai=false;//判断 是否已经有 展开项 view
    private HttpUtils httpUtils=new HttpUtils();

    private List<Boolean> zlist=new ArrayList<Boolean>();//记录 各个view的展开状态
    private TextView tv_date;//日期选择
    String time="2016-10-24";
    private List<View> vlist=new ArrayList<View>();
    private int[] date=new int[]{R.drawable.all,R.drawable.d15,R.drawable.d16,R.drawable.d17,R.drawable.d18,R.drawable.d19,R.drawable.d20};
    private int[] data_chose=new int[]{R.drawable.allyel,R.drawable.d15yel,R.drawable.d16yel,R.drawable.d17yel,R.drawable.d18yel,R.drawable.d19yel,R.drawable.d20yel};
    private ImageView ig15,ig16,ig17,ig18,ig19,ig20,igAll;
    private String[] date_chose=new String[]{"2016-05-15","2016-05-16","2016-05-17","2016-05-18","2016-05-19","2016-05-20"};

    private ImageView[] imgs;
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myticket);
        showDay();
        initUI();
        init();
        initData_web();
    }
    private RelativeLayout rl_title;
    private RelativeLayout rl_img;

    public void initUI(){
        rl_title= (RelativeLayout) findViewById(R.id.rl_title);
        rl_img= (RelativeLayout) findViewById(R.id.rl_img);
        tv_date= (TextView) findViewById(R.id.tv_date_se);
        Collections.sort(Utils.list_date);
        tv_date.setText(Utils.list_date.get(Utils.position));
        igAll= (ImageView) findViewById(R.id.igAll);
        ig15= (ImageView) findViewById(R.id.ig15);
        ig16= (ImageView) findViewById(R.id.ig16);
        ig17= (ImageView) findViewById(R.id.ig17);
        ig18= (ImageView) findViewById(R.id.ig18);
        ig19= (ImageView) findViewById(R.id.ig19);
        ig20= (ImageView) findViewById(R.id.ig20);
        imgs=new ImageView[]{igAll,ig15,ig16,ig17,ig18,ig19,ig20};
        doClick(position);



    }

    public void chose(View view){
        int id=view.getId();
        int position=0;
        switch (id){
            case R.id.igAll:
                position=0;
            break;
            case R.id.ig15:
                position=1;
                break;
            case R.id.ig16:
                position=2;
                break;
            case R.id.ig17:
                position=3;
                break;
            case R.id.ig18:
                position=4;
                break;
            case R.id.ig19:
                position=5;
                break;
            case R.id.ig20:
                position=6;
                break;
        }
        doClick(position);
    }
    //处理点击事件
    public void doClick(int position){
        for (int i=0;i<=imgs.length-1;i++){
            if(i==position){
                imgs[i].setImageResource(data_chose[i]);
            }else{
                imgs[i].setImageResource(date[i]);
            }
        }
        this.position=position;
        if(rl!=null){
            rl.removeAllViews();
        }
        Collections.sort(testList,mYComparator);
        test(testList);

    }


    //日期回退点击事件
    public void pre(View view){

        if(Utils.position<1){
            Utils.position=0;
        }else{
            Utils.position=Utils.position-1;
        }
        time=Utils.list_date.get(Utils.position);
        tv_date.setText(time);
        if(rl!=null){
            rl.removeAllViews();
        }
        test(testList);
    }
    //日期向后点击事件
    public void next(View view){
        if(Utils.position!=Utils.list_date.size()-1){
            Utils.position=Utils.position+1;
        }
        time=Utils.list_date.get(Utils.position);
        tv_date.setText(time);
        if(rl!=null){
            rl.removeAllViews();
        }
        test(testList);
    }
    //变更日期 并转换为string
    public String dateChangData(String date,int i){

        String str=tv_date.getText().toString();
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
        Date d=null;
        try {
            d =sdf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(d);
        calendar.add(Calendar.DAY_OF_MONTH,i);
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
        String t = s.format(calendar.getTime());
        tv_date.setText(t);
        time=t;
        return t;
    }

    public void init(){
        margin=(getWindowManager().getDefaultDisplay().getHeight())/size;
        height=(int)(getWindowManager().getDefaultDisplay().getHeight()/1.3f);
    }

    public void initView(){
        plist.clear();
        vlist.clear();
        posList.clear();
        rl= (RelativeLayout) findViewById(R.id.ll);
        for (int i=0;i<total;i++){
            View v1=View.inflate(this,R.layout.item_childview,null);
            if(i%4==0){
                v1.setBackgroundResource(R.drawable.lvlong);
            }else if(i%3==0){
                v1.setBackgroundResource(R.drawable.zilong);
            }else if(i%2==0){
                v1.setBackgroundResource(R.drawable.lanlong);
            }else{
                v1.setBackgroundResource(R.drawable.fenlong);
            }

            RelativeLayout.LayoutParams params1=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,height);
            params1.topMargin=margin*i;
            v1.setLayoutParams(params1);
            v1.setId(i);
            v1.setOnClickListener(this);

            setViewData(v1,i);

            vlist.add(v1);
            rl.addView(v1);
            plist.add(i);
            posList.add(params1.topMargin);
            zlist.add(false);
            map.put(i, v1);
        }


    }
    //给 每个view 设置数据
    public void setViewData(View v, final int position){
        TextView tv_start_time= (TextView) v.findViewById(R.id.tv_start_time);//开场时间
        TextView tv_title= (TextView) v.findViewById(R.id.tv_title);
        TextView tv_company= (TextView) v.findViewById(R.id.tv_company);
        TextView tv_company_e= (TextView) v.findViewById(R.id.tv_company_e);
        TextView tv_date= (TextView) v.findViewById(R.id.tv_date);
        TextView tv_time= (TextView) v.findViewById(R.id.tv_time);
        TextView tv_address= (TextView) v.findViewById(R.id.tv_address);
        TextView tv_address_e= (TextView) v.findViewById(R.id.tv_address_e);


        final Data data=temlist.get(position);
        tv_title.setText(data.getTitle());
        tv_company.setText(data.getUndertake());
        tv_company_e.setText(data.getUndertake_e());
        tv_date.setText(data.getStart_date());
        tv_time.setText(data.getEnter_time());
        tv_address.setText(data.getAddressA());
        tv_address_e.setText(data.getAddressA_e());
        tv_start_time.setText(data.getStart_time());
        final String showID=data.getID();
        ImageView ig_erweinma= (ImageView) v.findViewById(R.id.ig_erwei);
        LogUtils.log_E("二维码 宽高："+ig_erweinma.getWidth()+"height"+ig_erweinma.getHeight());
        ig_erweinma.setImageBitmap(Utils.createQRImage(erList.get(position), 800, 800));
        ImageView ig_zhuanzeng= (ImageView) v.findViewById(R.id.ig_zhuanzeng);
        ig_zhuanzeng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MyTicketActivity.this,DonationActivity.class);
                intent.putExtra("showID",showID);
                startActivity(intent);
            }
        });
        ImageView ig_gengduo= (ImageView) v.findViewById(R.id.ig_gengduo);

        ig_gengduo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.data=data;
                Intent intent=new Intent(MyTicketActivity.this,TicketDetialActivity.class);
                intent.putExtra("position",position);
                startActivity(intent);
                finish();
            }
        });


    }

    public void initData(){
        ylist.clear();
//
        for (int i=1;i<posList.size();i++){
            int a=posList.get(i)+height;

            ylist.add(a);
            LogUtils.log_E("默认位置："+a);
            LogUtils.log_E("ylist默认："+ylist.get(i-1));
        }
    }


    View view;
    @Override
    public void onClick(View v) {
//        LogUtils.log_E("getY====" + v.getY() + ";height:" + v.getHeight());

        int id=v.getId();
//                if(!isZhankai){
//                    animation_zhankai(id,v);
//                    isZhankai=true;
//                }else{
//                    animation_shouhui(id);
//                    isZhankai=false;
//                }

//        doAnimation(v);
            List<Integer> temlist=new ArrayList<Integer>();
            temlist.addAll(plist);
            animation_zhankai(id, v, temlist);
            animation_zhankai_id(v.getId());
    }



    //展开指定id 的view视图
    public void animation_zhankai_id(int zID){
        LogUtils.log_E("测试 展开 id");
        {
            final View mView=map.get(plist.get(zID));
            final int log = 0-(int)mView.getY();
            TranslateAnimation tr=new TranslateAnimation(mView.getX(),mView.getX(),0,log);
            tr.setDuration(1000);
            tr.setInterpolator(new AccelerateDecelerateInterpolator());
            tr.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }
                @Override
                public void onAnimationEnd(Animation animation) {
                    mView.clearAnimation();
                    int y=0;
                    RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,height);
                    params.topMargin=y;
                    mView.setLayoutParams(params);
                }
                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            mView.startAnimation(tr);}
//        {
//            final int log =mlog;
//            final View mView=map.get(plist.get(sID));
//            TranslateAnimation tr=new TranslateAnimation(mView.getX(),mView.getX(),0,log);
//            tr.setDuration(1000);
//            tr.setInterpolator(new AccelerateDecelerateInterpolator());
//            tr.setAnimationListener(new Animation.AnimationListener() {
//                @Override
//                public void onAnimationStart(Animation animation) {
//                }
//                @Override
//                public void onAnimationEnd(Animation animation) {
//                    mView.clearAnimation();
//                    int y=log;
//                    RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,height);
//                    params.topMargin=y;
//                    LogUtils.log_E("y============="+y+";;;;id="+mView.getId());
//                    mView.setLayoutParams(params);
//                }
//                @Override
//                public void onAnimationRepeat(Animation animation) {
//
//                }
//            });
//            mView.startAnimation(tr);}


    }

    //刷新列表
    private List<Integer> ylist=new ArrayList<Integer>();
    public void animation_zhankai(int id,View v,List<Integer> plist){
        plist.remove((Integer)id);
        for (int i=0;i<plist.size();i++){
            final View mView=map.get(plist.get(i));
            if(plist.get(i)!=id){

//                final int log=height-margin;
                final int pos=ylist.get(i);
                final int
                log=ylist.get(i)-(int)mView.getY()-margin;
                TranslateAnimation tr=new TranslateAnimation(mView.getX(),mView.getX(),0,log);
                tr.setDuration(1000);
                tr.setInterpolator(new AccelerateDecelerateInterpolator());
                tr.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }
                    @Override
                    public void onAnimationEnd(Animation animation) {
                        mView.clearAnimation();
                        int y=pos-margin;
                        RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,height);
                        params.topMargin=y;
                        mView.setLayoutParams(params);
                    }
                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                mView.startAnimation(tr);
            }else{
                int pianyi=(int)v.getY();
                int log=0-pianyi;
                TranslateAnimation tr=new TranslateAnimation(mView.getX(),0,0,log);
                tr.setDuration(1000);
                tr.setInterpolator(new AccelerateDecelerateInterpolator());
                tr.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        mView.clearAnimation();
                        int y = 0;
                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height);
                        params.topMargin = y;
                        mView.setLayoutParams(params);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                mView.startAnimation(tr);
            }

        }
    }

    public void animation_shouhui(int id){
        for (int i=0;i<plist.size();i++) {
            final View mView = map.get(plist.get(i));
            if (plist.get(i) != id) {
                final int mID=plist.get(i);
                final int log = 0-height+margin;
                TranslateAnimation tr = new TranslateAnimation(mView.getX(), mView.getX(), 0, log);
                tr.setDuration(1000);
                tr.setInterpolator(new AccelerateDecelerateInterpolator());
                tr.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        mView.clearAnimation();
                        int y = posList.get(mID);
                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height);
                        params.topMargin = y;
                        mView.setLayoutParams(params);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                mView.startAnimation(tr);
            }
        }
    }


    //处理导航条点击事件
    public void click(View view){
        int id=view.getId();
        switch (id){
            //返回键
            case R.id.ig_fanhui:
                finish();
                break;
        }
    }


    private List<Data> tlist=new ArrayList<Data>();
    private List<String> erList=new ArrayList<String>();
    public void initData_web(){

        httpUtils.configCurrentHttpCacheExpiry(1000 * 1);
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.PIAO_URL+Constans.userID, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    org.json.JSONObject jsonObject=new org.json.JSONObject(responseInfo.result);
                    String status=jsonObject.getString("status");
                    if("success".equals(status)){
                        LogUtils.log_E("测试"+responseInfo.result);
                        PiaoJiaJson pjson = JSONObject.parseObject(responseInfo.result, PiaoJiaJson.class);
                        List<PiaoJia> list = pjson.getResult();
                        if (list != null) {
                            initUI(list);
                        } else {
                            Utils.showToast("解析json出错");
                        }

                    }else{

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    LogUtils.log_E("epass异常"+e.getMessage());
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast("网络异常"+s);
            }
        });
    }
    private List<PiaoJiaData> testList=new ArrayList<PiaoJiaData>();
    public void initUI(List<PiaoJia> list){
        Utils.piaoJiaList.clear();
        Utils.shenQingList.clear();
        for (int i=0;i<list.size();i++){
            PiaoJiaData pdata=list.get(i).getData();
            String status=pdata.getStatus();
            if(status!=null){
                LogUtils.log_E("status="+status+"===");
                if(status.equals("1")||status.equals("4")){
                    if(pdata.getShow()!=null&&pdata.getShow().size()>0){
                        String show=pdata.getShow().get(0);
                        if(show.length()>10){
                            testList.add(pdata);
                            Data date= JSONArray.parseArray(show, Data.class).get(0);
                            tlist.add(date);
                            erList.add(pdata.getInfo());
                        }
                    }

                }else if(status.equals("2")||status.equals("3")){
                    Utils.piaoJiaList.add(pdata);
                }else if(status.equals("5")||status.equals("6")){
                    Utils.shenQingList.add(pdata);
                }


            }else{
            }

        }
        Collections.sort(testList,mYComparator);
        test(testList);
    }


   private Comparator<PiaoJiaData> mYComparator=new Comparator<PiaoJiaData>() {
       @Override
       public int compare(PiaoJiaData lhs, PiaoJiaData rhs) {
           String show=lhs.getShow().get(0);
           Data date= JSONArray.parseArray(show,DataJson.class).get(0).getData();
           String ti1="";
           String show2=rhs.getShow().get(0);
           Data date2=JSONArray.parseArray(show2,DataJson.class).get(0).getData();
           String t2="";
           if(position==0){
               ti1=date.getStart_date();
               t2=date2.getStart_date();
           }else{
               ti1=date.getStart_time();
               t2=date2.getStart_time();
           }
           return t2.compareTo(ti1);
       }
   };

    private List<Data> temlist;
    private int position;
    public void test(List<PiaoJiaData> tlist){
        erList.clear();
        temlist =new ArrayList<Data>();

            for (int n=0;n<tlist.size();n++){
                String show=tlist.get(n).getShow().get(0);
                Data date= JSONArray.parseArray(show,DataJson.class).get(0).getData();
                if(position!=0){

                    if(date.getStart_date().equals(date_chose[position-1])){
                        temlist.add(date);
                        erList.add(tlist.get(n).getInfo());
                    }
                }else{
                    temlist.add(date);
                    erList.add(tlist.get(n).getInfo());
                }

            }


        total=temlist.size();
        if(total>0){
            init();
            initView();
            initData();
        }
    }



    //默认显示最近的时间
    public void showDay(){

        Calendar ca = Calendar.getInstance();
        int year = ca.get(Calendar.YEAR);//获取年份
        int month=ca.get(Calendar.MONTH)+1;//获取月份
        int day=ca.get(Calendar.DATE);//获取日
        String mo="";
        String da="";
        if(month<10){
            mo="0"+month;
        }else{
            mo=month+"";
        }
        if(day<10){
            da="0"+day;
        }else{
            da=day+"";
        }
        LogUtils.log_E(year+"-"+mo+"-"+da);
        String date=year+"-"+mo+"-"+da;
        position=Utils.list_date.indexOf(date);
        if(position>-1){
            Utils.position=position;
        }else{
            if(date.compareTo(Utils.list_date.get(0))<=0){
                Utils.position=0;
                position=0;
            }else{
                if (date.compareTo(Utils.list_date.get(Utils.list_date.size()-1))>0){
                    Utils.position=Utils.list_date.size()-1;
                    position= Utils.list_date.size();
                }
            }
        }
    }




}

